<template lang="">
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 列表 -->
    <el-card>
      <el-row :gutter="20">
        <el-col :span="10">
          <el-input :clearable="true" @clear="clearSearch" placeholder="请输入内容" v-model="queryInfo.query" class="input-with-select" @keydown.enter.native="search">
            <el-button slot="append" icon="el-icon-search" @click="search"></el-button>
          </el-input>
        </el-col>
        <el-col :span="5">
          <el-button type="primary" @click="showAdd">添加用户</el-button>
        </el-col>
      </el-row>
      <!-- table表格 -->
      <el-table
        :data="usersList" border stripe
        style="width: 100%">
        <el-table-column  type="index"  label="#"></el-table-column>
        <el-table-column  prop="username"  label="用户名"  width="180"></el-table-column>
        <el-table-column prop="email"  label="邮箱"  width="180"></el-table-column>
        <el-table-column prop="mobile" label="电话" width="180"></el-table-column>
        <el-table-column prop="role_name" label="角色" width="180"></el-table-column>
        <el-table-column prop="mg_state" label="状态"  width="80">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.mg_state"
              @change="changeState(scope.row)"
              active-color="#13ce66"
              inactive-color="#ccc">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          width="180">
          <el-button type="primary" icon="el-icon-edit" size="small"></el-button>
          <el-button type="danger" icon="el-icon-delete" size="small"></el-button>
          <template slot-scope="scope">
            <el-button type="primary" icon="el-icon-edit" size="small" @click="showDialogEdit(scope.row)"></el-button>
            <el-button type="danger" icon="el-icon-delete" size="small" @click="showDialogDelete(scope.row)"></el-button>
            <el-button type="warning" icon="el-icon-setting" size="small" @click="showDialogRole(scope.row)"></el-button>
          </template>
         
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handlePageChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[2, 5, 10, 20]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>

    </el-card>

    <!-- 添加用户dialog -->
    <el-dialog
      title="添加用户"
      :visible.sync="addDialogVisible"
      width="50%">
      <el-form ref="addForm" :model="addForm" :rules="addRules" label-width="80px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>


      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addDialog">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配用户权限dialog -->
    <el-dialog
      title="分配角色"
      :visible.sync="roleDialogVisible"
      width="50%">
      <el-form ref="roleForm"  label-width="80px">
        <el-form-item label="当前用户" >
          <template slot-scope="scope">
            <span>{{user.username}}</span>
          </template>
        </el-form-item>
        <el-form-item label="当前角色">
          <template slot-scope="scope">
            <span>{{user.role_name}}</span>
          </template>
        </el-form-item>

        <el-form-item label="分配角色">
          <el-select v-model="roleId" placeholder="请选择" clearable filterable>
            <el-option
              v-for="item in roleList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id">
            </el-option>
          </el-select>

        </el-form-item>


      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="roleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="setRole">确 定</el-button>
      </span>

    </el-dialog>
  </div>
</template>
<script>
export default {
  name: "Users",
  data() {
    return {
      //添加用户
      addDialogVisible: false,
      addForm: {
        username: "",
        password: "",
        email: "",
        mobile: ""
      },
      addRules: {
        username: [
          { required: true, message: "请填写用户名", trigger: ['blur'] }
        ],
        password: [
          { required: true, message: "请填写密码", trigger: ['blur'] }
        ],
        email: [
          { required: true, message: "请填写邮箱", trigger: ['blur'] },
          { type: "email", message: "邮箱格式不正确", trigger: ['blur'] }
        ],
        mobile: [
          { required: true, message: "请填写手机号", trigger: ['blur'] }
        ],
      },
      //分配用户角色
      roleDialogVisible: false,
      roleList: [],
      roleId: "",
      user: {},   //用户信息

      //用户列表
      usersList: [],
      queryInfo: {
        query: "",
        pagenum: 1,
        pagesize: 10
      },
      total: 0

    }
  },
  async created() {
    this.getList()
  },
  computed: {

  },
  methods: {
    //显示修改对话框
    showDialogEdit() {

    },
    // 删除用户
    showDialogDelete() {

    },
    //显示分配权限对话框
    async showDialogRole(user) {
      this.roleDialogVisible = true;
      this.user = user

      //获取角色列表
      let { data: res } = await this.$axios({ url: "roles" }).catch(err => err)
      // console.log(res)
      this.roleList = res.data;




    },
    //分配用户角色
    async setRole() {
      let { data: res } = await this.$axios({
        url: `users/${this.user.id}/role`,
        method: "PUT",
        data: {
          rid: this.roleId
        }
      }).catch(err => err)
      console.log(res)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.roleDialogVisible = false;
      this.$message.success("成功分配用户角色")


    },
    //清空搜索框
    clearSearch() {
      this.queryInfo.query = ""
      this.queryInfo.pagenum = 1;
      this.getList()
    },
    //进行搜索
    search() {
      this.queryInfo.pagenum = 1;
      this.getList()
    },
    // 修改用户状态
    async changeState(row) {

      let { id, mg_state } = row;
      let { data: res } = await this.$axios({ url: `users/${id}/state/${mg_state}`, method: "PUT" }).catch(err => err)

      if (res.meta.status !== 200) return this.$message.error("修改用户状态失败")
      this.$message.success("状态修改成功")

    },
    //显示添加用户的对话框
    showAdd() {
      this.addDialogVisible = true;
    },
    //执行添加
    addDialog() {
      this.$refs.addForm.validate(async valid => {
        if (!valid) return this.$message.error("表单验证失败")
        let { data: res } = await this.$axios({ url: "users", method: "POST", data: this.addForm }).catch(err => err)

        if (res.meta.status !== 201) return this.$message.error("添加用户错误")
        this.usersList.push(res.data)
        this.$message.success("成功添加用户")
        this.addDialogVisible = false;

      })
    },

    //获取用户列表
    async getList() {
      let { data: { data, meta } } = await this.$axios({ url: "users", params: this.queryInfo }).catch(err => err)
      if (meta.status !== 200) return this.$message.error("获取用户失败")
      // console.log(meta)
      this.total = data.total;
      this.usersList = data.users;
    },
    //改变每页数量
    handleSizeChange(size) {
      this.queryInfo.pagesize = size
      this.getList()
    },
    //改变页码
    handlePageChange(page) {
      this.queryInfo.pagenum = page;
      this.getList()
    },
    async toggleState(user) {
      let { data: { data, meta } } = await this.$axios({
        url: `users/${user.id}/state/${user.mg_state}`,
        method: "PUT",
      }).catch(err => err)

      if (meta.status !== 200) return this.$message.error("修改状态失败")
      this.$message.success("成功修改状态")
    }

  }
}
</script>
<style lang="less">
.el-pagination {
  text-align: right;
  margin-top: 20px;
}

.el-card {
  margin-top: 20px;
}

.el-menu {
  border-right: 1px solid #333744;
}

.el-table {
  margin-top: 20px;
}
</style>